﻿using HandyControl.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using YY.Admin.Core.Models;
using YY.Admin.Services;
using YY.Admin.Views;

namespace YY.Admin.ViewModels
{
    public class MenuItem
    {
        public string Name { get; set; } = string.Empty;
        public string Icon { get; set; } = string.Empty;
        // 图标可以是资源键或路径数据
        public string ViewName { get; set; } = string.Empty;
        public ObservableCollection<MenuItem> Children { get; set; } = [];
    }

    public class MainViewModel : BaseViewModel
    {
        private readonly IAuthService _authService;
        private readonly IRegionManager _regionManager;
        private User? _currentUser;
        private MenuItem? _selectedMenuItem;

        public MainViewModel(IAuthService authService, IRegionManager regionManager)
        {
            _authService = authService;
            _regionManager = regionManager;
            Title = "后台管理系统";

            _currentUser = _authService.CurrentUser;
            _authService.UserChanged += OnUserChanged;

            InitializeMenuItems();

            LogoutCommand = new DelegateCommand(async () => await LogoutAsync());
            NavigateCommand = new DelegateCommand<MenuItem>(Navigate);
            // 默认导航到仪表盘
            // 延迟初始导航
            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                // 确保视图已加载后再导航
                _regionManager.RequestNavigate("ContentRegion", nameof(DashboardView));
            }), DispatcherPriority.ContextIdle);

        }

        public User? CurrentUser
        {
            get => _currentUser;
            set => SetProperty(ref _currentUser, value);
        }

        public ObservableCollection<MenuItem> MenuItems { get; } = [];

        public MenuItem? SelectedMenuItem
        {
            get => _selectedMenuItem;
            set => SetProperty(ref _selectedMenuItem, value);
        }

        public DelegateCommand LogoutCommand { get; }
        public DelegateCommand<MenuItem> NavigateCommand { get; }

        private void InitializeMenuItems()
        {
            MenuItems.Add(new MenuItem { Name = "仪表盘", Icon = "DashboardOutlined", ViewName = nameof(DashboardView) });

            var systemMenu = new MenuItem { Name = "系统管理", Icon = "HomeIcon" };
            systemMenu.Children.Add(new MenuItem { Name = "用户管理", Icon = "UserOutlined", ViewName = nameof(UserManagementView) });
            systemMenu.Children.Add(new MenuItem { Name = "角色管理", Icon = "TeamOutlined", ViewName = "RoleManagementView" });
            MenuItems.Add(systemMenu);
        }
        private void OnUserChanged(object? sender, User? user)
        {
            CurrentUser = user;
        }
        private void Navigate(MenuItem? menuItem)
        {
            if (menuItem != null && !string.IsNullOrEmpty(menuItem.ViewName))
            {
                try
                {
                    Debug.WriteLine($"导航到: {menuItem.ViewName}");
                    SelectedMenuItem = menuItem;
                    var region = _regionManager.Regions["ContentRegion"];
                    _regionManager.RequestNavigate("ContentRegion", menuItem.ViewName);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"导航错误: {ex.Message}");
                    Growl.Error($"无法打开 {menuItem.Name}: {ex.Message}");
                }
            }
        }

        private async Task LogoutAsync()
        {
            await _authService.LogoutAsync();

            // 返回登录窗口
            Application.Current.MainWindow?.Hide();
            var loginWindow = new LoginWindow();
            Application.Current.MainWindow = loginWindow;
            loginWindow.Show();
        }
    }
}
